/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');
var async  = require( 'async'); // 同步控制


// Schema 结构
var ItbMediaModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`media_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '图像ID',
  //`media_type` int(2) NOT NULL DEFAULT '0' COMMENT '0未知, 10音频, 20视频',
  //`user_type` int(1) NOT NULL DEFAULT '0' COMMENT '0后台; 1用户',
  //`user_id` bigint(20) NOT NULL COMMENT '用户ID',
  //`media_name` varchar(100) NOT NULL DEFAULT '' COMMENT '文件名',
  //`url` varchar(500) NOT NULL DEFAULT '' COMMENT 'URL地址',
  //`thumbs` text COMMENT '缩略图',
  //`duration` float NOT NULL DEFAULT '0' COMMENT '播放时长，单位秒',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',

};
ItbMediaModel.prototype = new ItbBaseModel();

// 取得表名
ItbMediaModel.prototype.getTableName = function(){
    return 'itb_media';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbMediaModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'media_id='+this.media_id;
};

/**
 * 按关键字查找
 * @param bForCnt: 1:求count, 0:取数据
 * @param userId[可选]: 按用户查找
 * @param key: 按名字条件
 * @param mediaType: 10:取音频, 20:取视频, 其他:取全部(默认)
 */
function sql_findByKey(bForCnt,userId,key,mediaType, pageNum, pageSize){
    var sql='';
    if(bForCnt) {
        sql+=' SELECT COUNT(*) AS cnt ';
    } else {
        sql+=' SELECT t.* ';
    }

    sql+=' FROM itb_media t '+
        ' WHERE t.del_flg=0 ';
    if(key && key.length>0) {
        sql+=' AND t.media_name LIKE "%'+(key||'')+'%" ';
    }
    if(userId>0) {
        sql+=' AND t.user_id='+userId;
    }
    if(mediaType==10 || mediaType==20) {
        sql+=' AND t.media_type='+mediaType;
    }

    if(!bForCnt) {
        sql += ' ORDER BY t.update_time DESC, t.media_id DESC ';
        if(typeof pageNum!='undefined' && pageNum != null && typeof pageSize!='undefined' && pageSize != null){
            var skipCnt = Number(pageNum)*Number(pageSize);
            sql += " LIMIT " + skipCnt + "," + Number(pageSize);
        }
    }

    return sql;
}

/**
 * 带关键字查找
 * @param userId[可选]: 按用户查找
 * @param key: 按名字条件
 * @param type: 10:取音频, 20:取视频, 其他:取全部(默认)
 * @param callback
 */
ItbMediaModel.prototype.findCountFromDBWithKey = function(userId, key, type, callback){
    var THIS = this;
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = sql_findByKey(true,userId,key,type);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            var total=0;
            if(error) {
                console.log(error);
            } else if (items) {
                console.log('find item');
                total = items[0].cnt;
            } else{
                console.log('find no one');
            }
            // 回调
            callback(error, total);
        });
    });
};

/**
 * 带关键字查找
 * @param userId[可选]: 按用户查找
 * @param key: 按名字条件
 * @param type: 10:取音频, 20:取视频, 其他:取全部(默认)
 * @param pageNum
 * @param pageSize
 * @param callback
 */
ItbMediaModel.prototype.findFromDBWithKey = function(userId,key,type,pageNum,pageSize,callback){
    var THIS = this;
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = sql_findByKey(false,userId,key,type,pageNum,pageSize);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });
    });
};

/**
 * 逻辑删除
 * @param userId
 * @param mediaId
 * @param callback
 */
ItbMediaModel.prototype.logicDeleteMediaByUser = function(userId,mediaId,callback){

    var THIS = this;
    var tableName = this.getTableName();
    //mysql update
    pool.pool.getConnection(function(err, connection) {
        // Use the connection

        var sql = 'UPDATE '+tableName+
            ' SET del_flg=1, update_time=sysdate(), update_by='+userId+
            ' WHERE media_id='+mediaId+' and user_id='+userId;
        var sqlValue = [ THIS ];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error) {
                console.log('ItbMediaModel.logicDeleteMedia error:'+error);
                callback(error);
            } else {
                callback(null);
            }
        });
    });
};

// 导出
module.exports = ItbMediaModel;